<?php

/**
 * SimplifyPHP Framework
 *
 * This file is part of SimplifyPHP Framework.
 *
 * SimplifyPHP Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * SimplifyPHP Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 * @copyright Copyright 2008 Rodrigo Rutkoski Rodrigues
 */

require_once ('phpthumb/phpthumb.class.php');

/**
 * PHP Thumb Component
 *
 * @author Rodrigo Rutkoski Rodrigues, <rutkoski@gmail.com>
 * @package simplify_components
 */
class PhpThumbComponent extends Component
{

  //public static $DEBUG = false;


  /**
   *
   * @var phpThumb
   */
  private $phpThumb = null;

  /**
   *
   * @var string
   */
  private $path = null;

  /**
   *
   * @var int
   */
  private $width = null;

  /**
   *
   * @var int
   */
  private $height = null;

  /**
   *
   * @var array
   */
  private $thumbParams = null;

  /**
   * Constructor.
   *
   * @param IApplicationController $app
   * @return void
   */
  public function __construct($params = null)
  {
    parent::__construct($params);

    $this->phpThumb = new phpThumb();

    $this->setParam('config_cache_directory', $this->config->get('cache:dir', '{app_dir}/cache'));
    $this->setParam('config_document_root', $this->config->get('files_dir', '{app_dir}/files'));
    $this->setParam('config_allow_src_above_docroot', true);
  }

  /**
   *
   * @param string $param
   * @param string $value
   * @return PhpThumbComponent
   */
  public function setParam($param, $value)
  {
    $this->phpThumb->$param = $value;
    return $this;
  }

  /**
   *
   * @param string $param
   * @param string $value
   * @return PhpThumbComponent
   */
  public function getParam($param)
  {
    return $this->phpThumb->$param;
  }

  /**
   *
   * @param $route
   * @return PhpThumbComponent
   */
  public function parse($route)
  {
    $args = preg_split('#/#', $route, - 1, PREG_SPLIT_NO_EMPTY);

    //// parse parameters
    // find path
    $path = array();
    do {
      $path[] = $args[0];
      $arg = array_shift($args);
    }
    while (count($args) && ! preg_match('/\.(jpe?g|png|gif)$/', $arg));

    $path = implode('/', $path);
    if (! sy_url_is_absolute($path) && strpos($path, '/') !== 0) {
      $path = '/' . $path;
    }
    $this->path = $path;

    // find size
    $size = count($args) ? array_shift($args) : '';
    preg_match('/^([0-9]+)?(?:x?([0-9]*))?/', $size, $size);
    $this->width = $size[1];
    $this->height = $size[2];

    // find aditional parameters
    $params = $args;
    $this->thumbParams = array();
    foreach ($params as $v) {
      preg_match('/^([^=]*)=?(.*)$/', $v, $param);
      $this->thumbParams[$param[1]] = $param[2];
    }

    return $this;
  }

  /**
   *
   * @param $width
   * @param $height
   * @param $params
   * @return unknown_type
   */
  public function output($width = null, $height = null, $params = null)
  {
    if (! empty($width)) $this->width = $width;
    if (! empty($height)) $this->height = $height;
    if (! empty($params)) $this->thumbParams = $params;

    $this->update();

    if (is_file($this->phpThumb->cache_filename)) {
      $this->outputFromCache();

      return;
    }

    if (! $this->phpThumb->GenerateThumbnail()) {
      throw new Exception($this->phpThumb->fatalerror);
    }

    if ($this->params->get('log_messages')) {
      sy_log('phpthumb', implode("\n->", $this->phpThumb->debugmessages), 0);
    }

    if ($this->phpThumb->RenderToFile($this->phpThumb->cache_filename) && is_readable($this->phpThumb->cache_filename)) {
      chmod($this->phpThumb->cache_filename, 0644);
      $this->outputFromCache();
    }

    echo $this->phpThumb->OutputThumbnail();
  }

  /**
   *
   * @param $width
   * @param $height
   * @param $params
   * @return unknown_type
   */
  public function getCacheFilename($width = null, $height = null, $params = null)
  {
    if (! empty($width)) $this->width = $width;
    if (! empty($height)) $this->height = $height;
    if (! empty($params)) $this->thumbParams = $params;

    $this->update();

    if (is_file($this->phpThumb->cache_filename)) {
      $filename = $this->phpThumb->cache_filename;
    }
    else {
      if (! $this->phpThumb->GenerateThumbnail()) {
        throw new Exception($this->phpThumb->fatalerror);
      }

      if ($this->params->get('log_messages')) {
        sy_log('phpthumb', implode("\n->", $this->phpThumb->debugmessages), 0);
      }

      if ($this->phpThumb->RenderToFile($this->phpThumb->cache_filename) && is_readable($this->phpThumb->cache_filename)) {
        $filename = $this->phpThumb->cache_filename;
      }
    }

    return basename($filename, '');
  }

  /**
   *
   * @param $file
   * @param $width
   * @param $height
   * @param $params
   * @return unknown_type
   */
  public function save($file, $width = null, $height = null, $params = null)
  {
    if (! empty($width)) $this->width = $width;
    if (! empty($height)) $this->height = $height;
    if (! empty($params)) $this->thumbParams = $params;

    $this->update();

    if (! $this->phpThumb->GenerateThumbnail()) {
      throw new Exception($this->phpThumb->fatalerror);
    }

    if ($this->params->get('log_messages')) {
      sy_log('phpthumb', implode("\n->", $this->phpThumb->debugmessages), 0);
    }

    if (! sy_path_is_absolute($file)) {
      $file = sy_fix_path($this->phpThumb->config_document_root . '/' . $file);
    }

    if (! $this->phpThumb->RenderToFile($file) || ! is_readable($file)) {
      sy_log('phpthumb', implode("\n->", $this->phpThumb->debugmessages), 0);
      throw new Exception($this->phpThumb->fatalerror);
    }

    chmod($file, 0644);

    return $file;
  }

  /**
   *
   * @param $file
   * @param $width
   * @param $height
   * @param $params
   * @return unknown_type
   */
  public function download($width = null, $height = null, $params = null)
  {
    $filename = $this->path;
    header('Content-Disposition: attachment; filename="' . $filename . '"');
  }

  /**
   *
   * @return void
   */
  private function update()
  {
    $this->phpThumb->setSourceFilename($this->path);

    if (! empty($this->width)) {
      $this->phpThumb->setParameter('w', $this->width);
    }

    if (! empty($this->height)) {
      $this->phpThumb->setParameter('h', $this->height);
    }

    //$this->phpThumb->setParameter('q', '99');


    foreach ($this->thumbParams as $param => $value) {
      $this->phpThumb->setParameter($param, $value);
    }

    $this->phpThumb->SetCacheFilename();
  }

  /**
   *
   * @return void
   */
  private function outputFromCache()
  {
    if ($getimagesize = @GetImageSize($this->phpThumb->cache_filename)) {
      header('Content-Type: ' . phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]));
    }

    echo file_get_contents($this->phpThumb->cache_filename);
  }

}

?>